/*
 * @Author: CaoTing
 * @Date: 2023-08-31 18:01:35
 * @Description:
 */
"use strict";

const http = require("http");
const crypto = require("crypto");

let baseUrl = "iotapi-ota-test.abupdate.com";
let cache = [];
let cacheExpire = 0;
let cache1 = null;
let cacheExpire1 = 0;
function registerDevice(args, callback) {
  if (Date.now() < cacheExpire) return callback(null, cache);
  let timestamp = Math.floor(Date.now() / 1000);
  let mid,
    oem,
    productId,
    productSecret,
    deviceType,
    platform,
    networkType,
    sdkversion,
    appversion,
    version,
    devSecret,
    models;
  if (args.length > 0) {
    mid = args[0];
    oem = args[1];
    productId = args[2];
    productSecret = args[3];
    deviceType = args[4];
    platform = args[5];
    networkType = args[6];
    sdkversion = args[7];
    appversion = args[8];
    version = args[9];
    models = args[10];
    devSecret = args[11];
  }
  console.log(devSecret);
  if (
    mid &&
    oem &&
    productId &&
    productSecret &&
    deviceType &&
    platform &&
    networkType &&
    sdkversion &&
    appversion &&
    version &&
    models &&
    (devSecret == "111" ||
      devSecret == 111 ||
      devSecret == undefined ||
      devSecret == "undefined")
  ) {
    let signContent = mid + productId + timestamp;
    let signKey = productSecret;
    let sign = crypto
      .createHmac("md5", signKey)
      .update(signContent)
      .digest("hex");
    let param = {
      mid,
      oem,
      models,
      platform,
      deviceType,
      timestamp,
      sign,
      sdkversion,
      appversion,
      version,
      networkType,
    };
    const postData = JSON.stringify(param);
    const options = {
      hostname: baseUrl,
      path: `/register/${productId}`,
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "Content-Length": Buffer.byteLength(postData),
      },
    };

    const req = http.request(options, (res) => {
      if (res.statusCode !== 200)
        return callback(
          new Error(`Request failed (status code: ${res.statusCode})`)
        );
      let rawData = "";
      res.on("data", (chunk) => (rawData += chunk));
      res.on("end", () => {
        let deviceData = JSON.parse(rawData)["data"];
        cache = [deviceData["deviceSecret"], deviceData["deviceId"]];
        console.log("注册：" + cache);
        cacheExpire = Date.now() + 10000;
        console.log("注册：" + cache);
        callback(null, cache);
      });
    });
    req.on("error", (err) => {
      console.log(err);
      callback(err);
    });
    req.write(postData);
    req.end();
  }

  return callback(null, cache);
}
function checkVersion(args, callback) {
  console.log(args);
  if (Date.now() < cacheExpire1) return callback(null, cache1);
  let timestamp = Math.floor(Date.now() / 1000);
  let mid, productId, version, deviceId, deviceSecret, reqType;
  if (args.length > 0) {
    mid = args[0];
    productId = args[1];
    version = args[2];
    deviceId = args[3];
    deviceSecret = args[4];
    reqType = args[5];
  }
  console.log('deviceSecret:'+deviceSecret)
  if (
    mid &&
    productId &&
    version &&
    deviceId &&
    (deviceSecret != 111 || deviceSecret != "111"||deviceSecret!='undefined'||deviceSecret!=undefined) &&
    (reqType == "1" || reqType == 1)
  ) {
    let signContent = deviceId + productId + timestamp;
    let signKey = deviceSecret;
    let sign = crypto
      .createHmac("md5", signKey)
      .update(signContent)
      .digest("hex");
    let param = {
      mid,
      sign,
      timestamp,
      version,
    };
    const postData = JSON.stringify(param);
    console.log('jcpd:'+postData);
    const options = {
      hostname: baseUrl,
      path: `/product/${productId}/${deviceId}`,
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "Content-Length": Buffer.byteLength(postData),
      },
    };

    const req = http.request(options, (res) => {
      console.log('jcre:');
      console.log(JSON.stringify(res))
      console.log(res)
      if (res.statusCode !== 200)
        return callback(
          new Error(`Request failed (status code: ${res.statusCode})`)
        );
      let rawData = "";
      res.on("data", (chunk) => (rawData += chunk));
      res.on("end", () => {
        let versionData = JSON.parse(rawData)["data"];
        vtData = JSON.stringify(versionData);
        cache1 = new Buffer(vtData).toString("base64");
        console.log("检测：" + cache1);
        cacheExpire1 = Date.now() + 10000;
        console.log("检测：" + cache1);
        callback(null, cache1);
      });
    });
    req.on("error", (err) => {
      console.log('jcer:');
      console.log(JSON.stringify(err));
      console.log(err)
      callback(err);
    });
    req.write(postData);
    req.end();
  }
  console.log(cache1);
  return callback(null, cache1);
}

exports.registerDevice = registerDevice;
exports.checkVersion = checkVersion;
